package org.example.command;

import org.example.model.HTMLDocument;
import org.jsoup.nodes.Element;

public class EditElementTextCommand implements CanUndoCommand {
    private String elementId;
    private HTMLDocument htmlDocument;

    private Element element;
    private final String newText;
    private String oldText;

    private EditElementTextCommand(HTMLDocument document, String elementId, String newText) {
        this.elementId = elementId;
        this.htmlDocument = document;
        this.newText = newText;
    }

    public static Command create(HTMLDocument document, String elementId, String newText) {
        return new EditElementTextCommand(document, elementId, newText);
    }

    @Override
    public boolean execute() {
        try {
            oldText = htmlDocument.getElementText(elementId);
            htmlDocument.editElementText(elementId,newText);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public void undo() {
        element.text(oldText);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        EditElementTextCommand other = (EditElementTextCommand) obj;
        return element.equals(other.element) && newText.equals(other.newText);
    }

    @Override
    public int hashCode() {
        return 31 * element.hashCode() + newText.hashCode();
    }

    @Override
    public String toString() {
        return "EditElementTextCommand{" + "element=" + element + ", newText='" + newText + "'}";
    }
}
